import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, DATE_FORMAT} from '../constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import {letterOfCreditQuery} from './api';
import {lcStatus, lcKind} from '../Enum';
import {conventEnumValueToString, conventSorter, formatDateTime} from '../utils';
import SelectAlert from '../common/SelectAlert';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {injectIntl, language} from './intl';
import moment from 'moment';
const FormItem = Form.Item;
const lcKindList = lcKind.toList(language);
class LetterOfCreditSelectPanel extends PureComponent {
    state = {
        lcCode: '',
        issueDate: [],
        issueBank: '',
        issueCountry: '',
        lcKind: undefined,
        data: {},
        message: '',
        showTags: false,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: [],
    }
    
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
        
    toggleShowTags=() => {
        this.setState({
            showTags: !this.state.showTags
        });
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        letterOfCreditQuery(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            dealerId: this.props.dealerId,
            brandId: this.props.brandId,
            currency: this.props.currency,
            lcCode: this.state.lcCode,
            issueDate: this.state.issueDate,
            issueBank: this.state.issueBank,
            issueCountry: this.state.issueCountry,
            lcKind: this.state.lcKind,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        const conventDate = condition => {
            const {issueDate, ...others} = condition;
            if(!issueDate || issueDate.length === 0) return condition;
            return {
                ...others,
                beginIssueDate: moment(issueDate[0]).toISOString(),
                endIssueDate: moment(issueDate[1]).toISOString(),
            };
        };
        this.onQuery(conventDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }

    onClickReset = () => {
        this.setState({
            lcCode: '',
            issueDate: undefined,
            issueBank: '',
            issueCountry: '',
            lcKind: undefined,
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'letterOfCreditSelectPanel.validate.addedItem',
                defaultMessage: '请选择信用证'
            }));
        this.props.onSelect(this.state.selectedRows[0]);
    }

    onSelectChange = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows,
            showConfirmButton: selectedRowKeys.length > 0
        });
    }

    onClearAll=() => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onDelete=id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    }

    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                sorter: true,
                dataIndex: 'dealerCode'
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.dealerName',
                    defaultMessage: '总代名称'
                }),
                dataIndex: 'dealerName',
                sorter: true,
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.lcCode',
                    defaultMessage: '信用证号码'
                }),
                dataIndex: 'lcCode'
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.versionCode',
                    defaultMessage: '最新版本号'
                }),
                dataIndex: 'versionCode'
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.issueCountry',
                    defaultMessage: '开证国家'
                }),
                dataIndex: 'issueCountry'
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.issueBank',
                    defaultMessage: '开证银行'
                }),
                dataIndex: 'issueBank'
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.issuePrice',
                    defaultMessage: '开证金额'
                }),
                dataIndex: 'issuePrice'
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.issueDate',
                    defaultMessage: '开证日期'
                }),
                dataIndex: 'issueDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.effectiveDate',
                    defaultMessage: '生效日期'
                }),
                dataIndex: 'effectiveDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.expirationDate',
                    defaultMessage: '失效日期'
                }),
                dataIndex: 'expirationDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: formatMessage({
                    id: 'letterOfCreditSelectPanel.column.lcStatus',
                    defaultMessage: '状态'
                }),
                dataIndex: 'lcStatus',
                render: text => conventEnumValueToString(lcStatus, text)
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            type: 'radio',
            fixed: true,
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys,
                    selectedRows
                });
            }
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const selectRows = this.state.selectedRows.length ? [{
            text: this.state.selectedRows[0].lcCode,
            value: this.state.selectedRows[0].id
        }] : [];
        return (
            <Modal
                title={formatMessage({
                    id: 'letterOfCreditSelectPanel.show.addedItemQuery',
                    defaultMessage: '信用证查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'letterOfCreditSelectPanel.lcCode',
                            defaultMessage: '信用证号码'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                name="lcCode"
                                value={this.state.lcCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'letterOfCreditSelectPanel.issueBank',
                            defaultMessage: '开证银行'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                name="issueBank"
                                value={this.state.issueBank}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'letterOfCreditSelectPanel.issueCountry',
                            defaultMessage: '开证国家'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                name="issueCountry"
                                value={this.state.issueCountry}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'letterOfCreditSelectPanel.lcKind',
                            defaultMessage: '信用证类型'
                        })} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="lcKind"
                                value={this.state.lcKind}
                                options={lcKindList}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'letterOfCreditSelectPanel.issueDate',
                            defaultMessage: '开证日期'
                        })} {...FORM_OPTIONS.item}>
                            <DateRangePicker
                                name="issueDate"
                                value={this.state.issueDate}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'letterOfCreditSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'letterOfCreditSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onClearAll}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    onRow={onRow}
                    {...TABLE}/>
            </Modal >
        );
    }
}

LetterOfCreditSelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    brandId: PropTypes.string,
    currency: PropTypes.number,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    onCancel: PropTypes.func
};

export default injectIntl(LetterOfCreditSelectPanel);
